package mephisto.rest.resources;

import java.io.IOException;

import org.restlet.Client;
import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

public class Authenticator extends Resource {

    public Authenticator(Context context, Request request, Response response) {
        super(context, request, response);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));

    }

    public boolean authenticate(String id, String password) {
        
        return true;
        
        /*if (id == null || password == null)
            return false;
        if (id.equals("arkub") && password.equals("kubar"))
            return true;
        return false;*/
    }

    public void acceptRepresentation(Representation entity) {
        if (entity != null) {

            if (MediaType.APPLICATION_WWW_FORM.equals(entity.getMediaType(), true)) {

                try {
                    Form form = getRequest().getEntityAsForm();

                    boolean authenticated = false;
                    String id = form.getFirstValue("id");
                    String password = form.getFirstValue("password");
                    authenticated = authenticate(id, password);

                    Representation rep = new StringRepresentation(String.valueOf(authenticated),
                            MediaType.TEXT_PLAIN);
                    getResponse().setEntity(rep);
                    getResponse().setStatus(Status.SUCCESS_OK);

                } catch (Exception e) {
                    getResponse().setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN));
                    getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                    e.printStackTrace();

                }
            }

        }

    }

  
    
    public static void main(String[] arg) {
        
        Client client = new Client(Protocol.HTTP);
        Form input = new Form();
        input.add("id", "arkub");
        input.add("password", "kubar");
        
        Response response = client.post("http://localhost:8182/authentication", input.getWebRepresentation());
        
        try {
            String responseText = response.getEntity().getText();
            System.out.println(responseText);
        } catch (IOException e) {
            e.printStackTrace();
        }
     
    }
}
